/*
 * @lc app=leetcode.cn id=61 lang=cpp
 *
 * [61] 旋转链表
 */

struct ListNode
{
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};
// @lc code=start

//

class Solution
{
public:
    ListNode *rotateRight(ListNode *head, int k)
    {
        if (!head || k == 0)
            return head;
        ListNode node;
        node.next = head;
        ListNode *last = &node, *prev = head, *cur = &node;
        int len = -1;
        for (int i = 0; i < k; i++)
        {
            last = last->next;
            if (last == nullptr)
            {
                last = &node;
                len = i;
                break;
            }
        }
        if (len != -1)
        {
            k = k % len;
            if (k == 0) return head;
            for (int i = 0; i < k; i++)
            {
                last = last->next;
            }
        }
        while (last->next)
        {
            cur = prev;
            prev = prev->next;
            last = last->next;
        }
        cur->next = nullptr;
        if (prev == head)
            return head;
        last->next = head;
        return prev;
    }
};
// @lc code=end
